<script lang="ts" setup name="InputNumber">
import { ElDialog } from 'element-plus'
interface Emits {
  (name: 'update:modelValue', value: number): void
}
const props = defineProps({
  ...ElDialog.props,
  modelValue: {
    type: Number,
    default: 0.0,
  },
  min: {
    type: Number,
    default: 0,
  },
  max: {
    type: Number,
    default: 0,
  },
  step: {
    type: Number,
    default: 1,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  w: {
    type: Number,
    default: 100,
  },
  controls: {
    type: Boolean,
    default: false,
  },
  align: {
    type: String,
    default: 'left',
  },
})

const emit = defineEmits<Emits>()

// const num = useVModel(props, 'modelValue', emit)

const displayValue = ref<number>(props.modelValue)
const precision = ref(2)

// 双向绑定 modelValue
watch(
  () => props.modelValue,
  (val) => {
    let str = val.toString()
    precision.value = 2
    if (!str.includes('.')) {
      displayValue.value = val.toFixed(2)
    } else {
      const [intPart, decimalPart] = str.split('.')
      if (decimalPart.length === 0) {
        str = `${intPart}.00`
      } else if (decimalPart.length === 1) {
        str = `${intPart}.${decimalPart}0`
      } else {
        str = `${intPart}.${decimalPart}`
        precision.value = decimalPart.length
      }
      displayValue.value = Number(str)
    }
  }
)

const handleFocus = (e: FocusEvent) => {
  let str = displayValue.value.toString()
  if (str.includes('.')) {
    const [intPart, decimalPart] = str.split('.')
    precision.value = decimalPart.length > 0 ? decimalPart.length : 0
    if (/^0+$/.test(decimalPart)) {
      precision.value = 0
      str = intPart
    }
  }
  displayValue.value = Number(str)
}
const handleBlur = (e: FocusEvent) => {
  // 保留两位小数规则
  let str = displayValue.value.toString()
  if (!str.includes('.')) {
    str = str + '.00'
    precision.value = 2
    console.log(1)
  } else {
    const [intPart, decimalPart] = str.split('.')
    if (decimalPart.length === 0) {
      str = `${intPart}.00`
      precision.value = 2
      console.log(2)
    } else if (decimalPart.length === 1) {
      str = `${intPart}.${decimalPart}0`
      precision.value = 2
      console.log(3)
    } else {
      console.log(1)
      str = `${intPart}.${decimalPart}`
      precision.value = decimalPart.length
    }
  }
  displayValue.value = Number(str)
  emit('update:modelValue', displayValue.value)
}

// computed style，带 !important
const inputStyle = computed(() => `width: ${props.w}% !important`)
</script>

<template>
  <div>
    <el-input-number
      v-model="displayValue"
      :align="props.align"
      :controls="props.controls"
      :disabled="props.disabled"
      :min="props.min"
      :precision="precision"
      :step="props.step"
      :style="inputStyle"
      @blur="handleBlur"
      @focus="handleFocus"
    />
  </div>
</template>

<style lang="scss" scoped></style>
